package com.wakala.employment.fragment.finder;

import static com.xuexiang.xaop.consts.PermissionConsts.LOCATION;
import static com.xuexiang.xui.utils.XToastUtils.toast;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.FloatLayoutHelper;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.alibaba.android.vlayout.layout.StickyLayoutHelper;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.github.florent37.viewtooltip.ViewTooltip;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.stx.xmarqueeview.XMarqueeView;
import com.wakala.employment.R;
import com.wakala.employment.adapter.base.broccoli.BroccoliSimpleDelegateAdapter;
import com.wakala.employment.adapter.base.delegate.SingleDelegateAdapter;
import com.wakala.employment.adapter.bean.JobInfoPage;
import com.wakala.employment.adapter.bean.JobInfoSearchRequest;
import com.wakala.employment.adapter.entity.JobInfoVo;
import com.wakala.employment.adapter.marquee.MarqueeView2Adapter;
import com.wakala.employment.adapter.marquee.MarqueeViewAdapter;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.bean.EventKey;
import com.wakala.employment.core.constants.Constants;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentJobFinderBinding;
import com.wakala.employment.fragment.other.RealNameAuthFragment;
import com.wakala.employment.fragment.other.UserTaskCenterFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.CategoryMenuVo;
import com.wakala.employment.utils.DemoDataProvider;
import com.wakala.employment.utils.ImageUtils;
import com.wakala.employment.utils.LocationService;
import com.wakala.employment.utils.Utils;
import com.xuexiang.citypicker.CityPicker;
import com.xuexiang.citypicker.adapter.OnLocationListener;
import com.xuexiang.citypicker.adapter.OnPickListener;
import com.xuexiang.citypicker.model.City;
import com.xuexiang.citypicker.model.HotCity;
import com.xuexiang.citypicker.model.LocateState;
import com.xuexiang.rxutil2.rxbus.RxBusUtils;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xui.widget.toast.XToast;
import com.xuexiang.xutil.app.AppUtils;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.display.ScreenUtils;
import com.xuexiang.xutil.tip.ToastUtils;
import com.yechaoa.yutils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import me.samlss.broccoli.Broccoli;

/**
 * qiu
 * A simple {@link Fragment} subclass.
 * 找活
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class JobFinderFragment extends BaseFragment<FragmentJobFinderBinding> implements View.OnClickListener {
    public static final String TAG = JobFinderFragment.class.getSimpleName();

    private BroccoliSimpleDelegateAdapter<JobInfoVo> mJobsAdapter;
    private List<JobInfoVo> jobInfoVoList = new ArrayList<>();

    //最新
    SuperButton ssBtnLatest;
    //推荐
    SuperButton ssBtnRecommend;
    //附近
    SuperButton ssBtnNearby;
    SuperButton ssBtnRegionAddress;

    List<HotCity> mHotCities = null;

    ViewTooltip.TooltipView viewTooltip = null;
    /**
     * jonInfo查询条件
     */
    private JobInfoSearchRequest jobInfoSearchRequest = new JobInfoSearchRequest();
    private HorizontalScrollView horizontalScrollView;
    private LinearLayout container;

    int mAnim = 0;
    int mTheme;
    boolean mEnableAnimation = false;
    boolean isInit = false;

    int currentPage = 1;
    int pageSize = 10;

    @NonNull
    @Override
    protected FragmentJobFinderBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        Log.i(TAG, "JobFinderFragment viewBinding");
        return FragmentJobFinderBinding.inflate(inflater, container, attachToRoot);
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.xui_config_color_light));
        return null;
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        XToast.Config.get().setTextSize(16)
                .setAlpha(10)
                //位置设置为居中
                .setGravity(Gravity.CENTER);
        //
        mHotCities = new ArrayList<>();
        mHotCities.add(new HotCity("北京", "北京", "101010100"));
        mHotCities.add(new HotCity("上海", "上海", "101020100"));
        mHotCities.add(new HotCity("广州", "广东", "101280101"));
        mHotCities.add(new HotCity("深圳", "广东", "101280601"));
        mHotCities.add(new HotCity("杭州", "浙江", "101210101"));
        mTheme = R.style.DefaultCityPickerTheme;

        getActivity().setTheme(mTheme);
        //给“我要招人” 按钮加上tooltip
        /*viewTooltip = ViewTooltip
                .on(this ,binding.ssBtnJob)
                .autoHide( false, 1000)
                .clickToHide(true )
                .align(ViewTooltip.ALIGN.CENTER)
                .position(ViewTooltip.Position.BOTTOM)
                .text("点击可切换到篮板端，快速招人")
                .textColor(Color.WHITE)
                .color(getResources().getColor(R.color.xui_config_color_blue))
                .corner(15)
                .distanceWithView(40)
                .arrowWidth(15)
                .arrowHeight(15)
                //change the opening animation
                // .animation(new ViewTooltip.TooltipAnimation(){...})
                //listeners
                .onDisplay(new ViewTooltip.ListenerDisplay() {
                    @Override
                    public void onDisplay(View view) {

                    }
                })
                .onHide(new ViewTooltip.ListenerHide() {
                    @Override
                    public void onHide(View view) {

                    }
                })
                .show();*/
    }

    private void addTag(com.xuexiang.xui.widget.flowlayout.FlowLayout linearLayout, String tagName, String themName) {
        TextView textView = new TextView(getContext());
        ViewGroup.MarginLayoutParams textViewParams = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, // 宽度
                ViewGroup.LayoutParams.WRAP_CONTENT  // 高度
        );
        textViewParams.setMargins(Dp2Px(getContext(), 5), 0, 0, Dp2Px(getContext(), 5));
        textView.setPadding(Dp2Px(getContext(), 2), Dp2Px(getContext(), 2), Dp2Px(getContext(), 2), Dp2Px(getContext(), 2));
        textView.setLayoutParams(textViewParams);
        textView.setText(tagName);
        textView.setTextSize(12.0f);

        if ("blue".equals(themName)) {
            textView.setBackgroundColor(getResources().getColor(R.color.tag_bg_blue));
            textView.setTextColor(getResources().getColor(R.color.colorPrimary));
        } else if ("gray".equals(themName)) {
            textView.setBackgroundColor(getResources().getColor(R.color.tag_bg_gray));
            textView.setTextColor(getResources().getColor(R.color.tag_text_gray));
        } else {
            textView.setBackgroundColor(getResources().getColor(R.color.tag_bg_blue));
            textView.setTextColor(getResources().getColor(R.color.colorPrimary));
        }
        linearLayout.addView(textView);
    }

    /**
     * 顶部菜单区域动态绑定菜单数据
     */
    private void bindKingMenu(CategoryMenuVo categoryMenuVo) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Dp2Px(getContext(), 75), Dp2Px(getContext(), 65));
        layoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
        LinearLayout linearLayout = new LinearLayout(getContext());
        linearLayout.setOrientation(LinearLayout.VERTICAL); // 设置为垂直
        linearLayout.setLayoutParams(layoutParams); // 设置布局参数
        linearLayout.setGravity(Gravity.CENTER);
        ImageView imageView = new ImageView(getContext());
        imageView.setImageResource(R.drawable.icon_img_loading);
        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        linearLayout.addView(imageView);
        //
        if (null != categoryMenuVo) {
            //加载图片
            RequestOptions options = new RequestOptions().centerCrop().placeholder(R.color.color_f4).diskCacheStrategy(DiskCacheStrategy.ALL);
            String imgUrl = categoryMenuVo.getIcon();
            /*MediaLoader.get().displayImage(this, categoryMenuVo.getIcon(), imageView, new ISimpleTarget(){
                @Override
                public void onResourceReady() {

                }

                @Override
                public void onLoadFailed(@Nullable Drawable drawable) {
                    if (drawable != null) {
                        imageView.setImageDrawable(drawable);
                    }
                }
            });*/
            Glide.with(getContext()).asBitmap().load(imgUrl).placeholder(R.drawable.icon_img_loading).override(Dp2Px(getContext(), 36), Dp2Px(getContext(), 36)).transform(new RoundedCorners(10)).apply(options).into(imageView);
        } else {
            imageView.setImageResource(R.drawable.icon_king_menu_color3);
        }

       /* Glide.with(getContext()).asBitmap()
                .load(imgUrl)
                .addListener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                        return false;
                    }
                    @Override
                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                        //根据图片宽高比设置容器的高度

                        return false;
                    }
                })
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                .transform(new RoundedCorners(10))
                .apply(options)
                .into(imageView);*/
        // 使用Glide库加载SVG图片
        // 使用Glide加载SVG图像
        TextView textView = new TextView(getContext());
        ViewGroup.MarginLayoutParams textViewParams = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, // 宽度
                ViewGroup.LayoutParams.WRAP_CONTENT  // 高度
        );
        textViewParams.setMargins(0, Dp2Px(getContext(), 5), 0, 0);
        textView.setLayoutParams(textViewParams);
        if (null != categoryMenuVo) {
            textView.setText(categoryMenuVo.getName());
        } else {
            textView.setText("全部分类");
        }

        textView.setTextSize(12.0f);
        textView.setTextColor(getResources().getColor(R.color.black));
        linearLayout.addView(textView);

        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != categoryMenuVo) {
                    ToastUtils.toast(categoryMenuVo.getName());
                    if (categoryMenuVo.getTarget() == 1) {
                        //工种
                        //跳转到招聘信息列表页面JobListFragment
                        openNewPage(JobListFragment.class, "data", categoryMenuVo);
                    } else if (categoryMenuVo.getTarget() == 2) {
                        //职位标签，跳转到招聘信息列表页面JobListFragment，查询职位关键字
                        openNewPage(JobListFragment.class, "data", categoryMenuVo);
                    } else if (categoryMenuVo.getTarget() == 3) {
                        //关键字 title关键字，关键字标签
                        //职位标签，跳转到招聘信息列表页面JobListFragment，查询招工信息标题关键字，关键字配置
                        openNewPage(JobListFragment.class, "data", categoryMenuVo);
                    } else if (categoryMenuVo.getTarget() == 4) {
                        //跳转到webView页面，通过webview 打开url
                        //检查url字段是否符合URL正则表达
                        Utils.goWeb(getContext(), categoryMenuVo.getUrl());
                    }
                } else {
                    ToastUtils.toast("所有种类");
                    //跳转到所有工种选择页面
                    openNewPage(JobCategoryFragment.class, "type", "JOBFINDER");
                }

            }
        });
        container.addView(linearLayout);
    }

    private JobFinderFragment getFragment() {
        return this;
    }

    @Override
    protected void initViews() {
      /*  binding.ssBtnLatest.setOnClickListener(this);
        binding.ssBtnRecommend.setOnClickListener(this);
        binding.ssBtnNearby.setOnClickListener(this);*/
        jobInfoVoList = DemoDataProvider.getEmptyJobInfo();
        binding.ssBtnRegion.setOnClickListener(this);

        // 1.设置VirtualLayoutManager
        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(getContext());
        binding.recyclerView.setLayoutManager(virtualLayoutManager);

        // 2.设置RecycledViews复用池大小（可选）
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 20);
        binding.recyclerView.setRecycledViewPool(viewPool);

        /**
         * 1.顶部菜单
         */
        SingleDelegateAdapter menuAdapter = new SingleDelegateAdapter(R.layout.adapter_vlayou_king_menu_item) {
            @Override
            public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
                if (!isInit) {
                    horizontalScrollView = holder.findViewById(R.id.horizontalScrollView);
                    container = holder.findViewById(R.id.horizontalScrollViewItemContainer);
                    //bindKingMenu();
                    //
                    isInit = true;
                }

            }

        };
        /**
         * 2.顶部banner-加微信
         */
        SingleDelegateAdapter bannerWeiXinAdapter = new SingleDelegateAdapter(R.layout.adapter_vlayou_banner_weixin_item) {
            @Override
            public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
                List<String> data = new ArrayList<>();
                data.add("免费加入本地招人找活群");
                data.add("附件找人找活信息推送");
                data.add("优质创业项目推荐");
                data.add("超多赚钱机会分享");

                XMarqueeView xMarqueeView = (XMarqueeView) holder.findViewById(R.id.marquee);
                try {
                    xMarqueeView.setAdapter(new MarqueeViewAdapter(data, getContext()));
                } catch (Exception e) {
                    //catchsetAdapter重复设置adapter抛出异常的异常。
                    Log.w("", e.getMessage());
                }

                //刷新数据
                //marqueeViewAdapter.setData(data);
                holder.click(R.id.rb_wei_chat, v -> {
                    //打开关注微信界面
                    /*if (AppUtils.isInstallApp("com.tencent.mm")) {
                        try {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse("weixin://dl/officialaccount?officialAccountID=" + "miaoyankeji"));
                            startActivity(intent);
                        } catch (Exception e) {
                            // 处理异常情况
                            PopTip.show("打开微信失败");
                        }
                    } else {
                        PopTip.show("本机没有安装微信");
                    }*/
                    ToastUtil.showToast("下滑关闭当前窗口");
                    new XPopup.Builder(getContext()).asCustom(new BottomPopupView(requireContext()) {
                        @Override
                        protected int getImplLayoutId() {
                            return R.layout.dialog_invite_view;
                        }

                        @Override
                        protected void onCreate() {
                            super.onCreate();

                        }
                    }).show();
                });
            }
        };
        /**
         * 2.1
         */
        SingleDelegateAdapter bannerAuthTipAdapter = new SingleDelegateAdapter(R.layout.adapter_vlayou_banner_auth_tip_item) {
            @Override
            public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
                List<String> data = new ArrayList<>();
                data.add("完成实名认证，获得更多关注机会！去认证 >>");
                data.add("马上加入会员，快速找到好工作 >>");
                data.add("优质创业项目推荐,自己当老板赚大钱 >>");
                data.add("超多赚钱机会分享 >>");

                XMarqueeView xMarqueeView = (XMarqueeView) holder.findViewById(R.id.marquee2);
                try {
                    xMarqueeView.setAdapter(new MarqueeView2Adapter(data, getContext()));
                } catch (Exception e) {
                    Log.w("", e.getMessage());
                }
                holder.click(R.id.card_view4, view -> openNewPage(RealNameAuthFragment.class));
            }
        };
        /**
         * 3.条件过滤-吸顶布局
         */
        StickyLayoutHelper layoutHelper = new StickyLayoutHelper();
        //设置顶部固定
        layoutHelper.setStickyStart(true);
        // 设置偏移量(距离顶部或底部)
        //layoutHelper.setOffset(-50);
        // 宽与高的比例
        //layoutHelper.setAspectRatio(4);
        //设置背景色
        layoutHelper.setBgColor(getResources().getColor(R.color.black));
        //layoutHelper.setPadding(0, 16, 0, 0);
        layoutHelper.setMargin(0, 0, 0, 0);
        //layoutHelper.setZIndex(9999);
        // --吸顶布局--
        SingleDelegateAdapter filterAdapter = new SingleDelegateAdapter(R.layout.adapter_vlayou_filter_item, layoutHelper) {
            @Override
            public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
                ssBtnLatest = holder.findViewById(R.id.ssBtn_latest);
                ssBtnRecommend = holder.findViewById(R.id.ssBtn_recommend);
                ssBtnNearby = holder.findViewById(R.id.ssBtn_nearby);
                ssBtnRegionAddress = holder.findViewById(R.id.ssBtn_region_address);
                //holder.text(R.id.tv_title, "资讯");
                //holder.text(R.id.tv_action, "更多");
                holder.click(R.id.ssBtn_latest, v -> {
                    //最新
                    ssBtnLatest.setTextAppearance(R.style.SuperButton_Select);
                    ssBtnLatest.setTextColor(getResources().getColor(R.color.colorPrimary));
                    ssBtnRecommend.setTextColor(getResources().getColor(R.color.black_light_T9));
                    ssBtnNearby.setTextColor(getResources().getColor(R.color.black_light_T9));

                    ssBtnLatest.setBackgroundColor(getResources().getColor(R.color.select_btn_color_normal));
                    ssBtnRecommend.setBackgroundColor(getResources().getColor(R.color.xui_transparent));
                    ssBtnNearby.setBackgroundColor(getResources().getColor(R.color.xui_transparent));

                    ssBtnLatest.setShapeCornersRadius(12f);
                    ssBtnLatest.setTextSize(14);
                });
                holder.click(R.id.ssBtn_recommend, v -> {
                    //推荐
                    ssBtnLatest.setTextColor(getResources().getColor(R.color.black_light_T9));
                    ssBtnRecommend.setTextColor(getResources().getColor(R.color.colorPrimary));
                    ssBtnNearby.setTextColor(getResources().getColor(R.color.black_light_T9));


                    ssBtnLatest.setBackgroundColor(getResources().getColor(R.color.xui_transparent));
                    ssBtnRecommend.setBackgroundColor(getResources().getColor(R.color.select_btn_color_normal));
                    ssBtnNearby.setBackgroundColor(getResources().getColor(R.color.xui_transparent));

                    ssBtnRecommend.setShapeCornersRadius(Float.intBitsToFloat(30));
                });
                holder.click(R.id.ssBtn_nearby, v -> {
                    //附近
                    ssBtnLatest.setTextColor(getResources().getColor(R.color.black_light_T9));
                    ssBtnRecommend.setTextColor(getResources().getColor(R.color.black_light_T9));
                    ssBtnNearby.setTextColor(getResources().getColor(R.color.colorPrimary));

                    ssBtnLatest.setBackgroundColor(getResources().getColor(R.color.xui_transparent));
                    ssBtnRecommend.setBackgroundColor(getResources().getColor(R.color.xui_transparent));
                    ssBtnNearby.setBackgroundColor(getResources().getColor(R.color.select_btn_color_normal));

                    ssBtnNearby.setShapeCornersRadius(12f);
                    ssBtnNearby.setShapeGradientGradientRadius(15);
                    //检查位置授权
                    checkLocationPermission();
                });


                holder.click(R.id.ssBtn_region_address, v -> {
                    pickCity();
                });
            }
        };


        //资讯
        /**
         * 4.Job资讯
         */
        mJobsAdapter = new BroccoliSimpleDelegateAdapter<JobInfoVo>(R.layout.adapter_jobs_card_view_list_item, new LinearLayoutHelper(), jobInfoVoList) {
            @Override
            protected void onBindData(RecyclerViewHolder holder, JobInfoVo model, int position) {
                if (model != null) {
                    holder.text(R.id.tv_user_name, model.getLinkMan());
                    holder.text(R.id.tv_tag, model.getJobTags());
                    holder.text(R.id.tv_title, model.getTitle());
                    holder.text(R.id.tv_summary, model.getContent());
                    holder.text(R.id.tv_praise, model.getPublishTime().substring(0, 16));
                    holder.text(R.id.tv_comment, "评论");
                    holder.text(R.id.tv_read, "阅读量 " + 0);
                    holder.image(R.id.iv_image, model.getUser().getAvatar());
                    holder.text(R.id.tv_location, model.getJobUserAddress().getCity() + model.getJobUserAddress().getDistrict() + model.getJobUserAddress().getDetail());

                    //holder.click(R.id.card_view, v -> Utils.goWeb(getContext(), model.getDetailUrl()));
                    holder.click(R.id.card_view, view -> {
                        openNewPage(JobInfoFragment.class, "jobInfoId", model.getId());
                        //openNewPage(JobInfoFragment.class, "jobInfo", model);
                    });
                    //Tag容器
                    com.xuexiang.xui.widget.flowlayout.FlowLayout tagLayout = holder.findViewById(R.id.tag_layout);
                    tagLayout.removeAllViews();
                    //判断实名认证
                    if (model.getUser().getRealNameAuth()) {
                        addTag(tagLayout, "已实名", "blue");
                    }
                    if (model.getUser().getEnterpriseAuth()) {
                        addTag(tagLayout, "企业认证", "blue");
                    }
                    if (!StringUtils.isEmpty(model.getJobCategoryName())) {
                        addTag(tagLayout, model.getJobCategoryName(), "blue");
                    }
                    //结算方式
                    if (!StringUtils.isEmpty(model.getSettlementModeName())) {
                        addTag(tagLayout, model.getSettlementModeName(), "blue");
                    }
                    //添加薪资
                    addTag(tagLayout, model.getSalaryName(), "blue");
                    for (String tag : model.getJobTagsList()) {
                        addTag(tagLayout, tag, "blue");
                    }
                    for (String tag : model.getWelfareTagsList()) {
                        addTag(tagLayout, tag, "gray");
                    }
                    for (String tag : model.getKeywordsList()) {
                        addTag(tagLayout, tag, "gray");
                    }
                    /*TagContainerLayout mTagContainerLayout = (TagContainerLayout) holder.findViewById(R.id.flowlayout_tgs);
                    mTagContainerLayout.addTag("免费午餐");
                    mTagContainerLayout.addTag("朝九晚五");
                    mTagContainerLayout.addTag("免费午餐");
                    mTagContainerLayout.addTag("朝九晚五");
                    mTagContainerLayout.addTag("免费午餐");
                    mTagContainerLayout.addTag("朝九晚五");*/


                }
            }

            @Override
            protected void onBindBroccoli(RecyclerViewHolder holder, Broccoli broccoli) {
                broccoli.addPlaceholders(holder.findView(R.id.tv_user_name), holder.findView(R.id.tv_tag), holder.findView(R.id.tv_title), holder.findView(R.id.tv_summary), holder.findView(R.id.tv_praise), holder.findView(R.id.tv_comment), holder.findView(R.id.tv_read), holder.findView(R.id.iv_image), holder.findView(R.id.btn_link_boss), holder.findView(R.id.tag_layout), holder.findView(R.id.iv_location), holder.findView(R.id.tv_location));
            }
        };
        /**
         * 5.漂浮组件
         */
        FloatLayoutHelper floatLayoutHelper = new FloatLayoutHelper();
        //floatLayoutHelper.setDefaultLocation(ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight());
        floatLayoutHelper.setX(ScreenUtils.getScreenWidth()-100);
        Double threePartOfHeight = ScreenUtils.getScreenHeight()*0.6;
        int height = ScreenUtils.getScreenHeight()-threePartOfHeight.intValue();
        floatLayoutHelper.setY(height);
        SingleDelegateAdapter floatAdapter = new SingleDelegateAdapter(R.layout.adapter_vlayout_float_item, floatLayoutHelper) {
            @Override
            public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
                View floatView = holder.getView(R.id.ll_float_01);
                ImageView imageView = holder.getImageView(R.id.ic_float_content);
                imageView.setImageResource(R.drawable.icon_float_img01);
                holder.click(R.id.ic_float_close, view -> {
                    //点击关闭漂浮组件按钮
                    floatView.setVisibility(View.GONE);
                });
                holder.itemView.setOnClickListener(v -> {
                    //点击了漂浮组件，打开配置的链接
                    //XToastUtils.toast("点击了悬浮窗");
                    openNewPage(UserTaskCenterFragment.class);
                });
            }
        };
        /**
         * 6.漂浮组件
         */
        FloatLayoutHelper floatLayoutHelper2 = new FloatLayoutHelper();
        //floatLayoutHelper.setDefaultLocation(ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight());
        floatLayoutHelper2.setX(ScreenUtils.getScreenWidth()-100);
        Double threePartOfHeight2 = ScreenUtils.getScreenHeight()*0.5;
        int height2 = ScreenUtils.getScreenHeight()-threePartOfHeight2.intValue();
        floatLayoutHelper2.setY(height2);
        SingleDelegateAdapter floatAdapter2 = new SingleDelegateAdapter(R.layout.adapter_vlayout_float_item, floatLayoutHelper2) {
            @Override
            public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
                View floatView = holder.getView(R.id.ll_float_01);
                ImageView imageView = holder.getImageView(R.id.ic_float_content);
                imageView.setImageResource(R.drawable.icon_float_img02);
                holder.click(R.id.ic_float_close, view -> {
                    //点击关闭漂浮组件按钮
                    floatView.setVisibility(View.GONE);
                });
                holder.itemView.setOnClickListener(v -> {
                    //点击了漂浮组件，打开配置的链接
                    //XToastUtils.toast("点击了悬浮窗");
                    openNewPage(UserTaskCenterFragment.class);
                });
            }
        };

        DelegateAdapter delegateAdapter = new DelegateAdapter(virtualLayoutManager);
        delegateAdapter.addAdapter(floatAdapter);
        delegateAdapter.addAdapter(floatAdapter2);
        delegateAdapter.addAdapter(menuAdapter);
        delegateAdapter.addAdapter(bannerWeiXinAdapter);
        delegateAdapter.addAdapter(bannerAuthTipAdapter);
        delegateAdapter.addAdapter(filterAdapter);
        delegateAdapter.addAdapter(mJobsAdapter);

        binding.recyclerView.setAdapter(delegateAdapter);
    }


    @Override
    protected void initListeners() {
        //点击搜索框
        binding.ltSearchBox.setOnClickListener(this);
        //我要招工
        binding.ssBtnJob.setOnClickListener(this);
        //下拉刷新
        binding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            currentPage = 1;
            jobInfoSearchRequest.setPage(currentPage);
            getJobInfoList("fresh");
            getKingMenuList(1, 0);
        });
        //上拉加载
        binding.refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            //int currentPage = mJobsAdapter.getItemCount() / pageSize + 1;
            currentPage++;
            jobInfoSearchRequest.setPage(currentPage);
            getJobInfoList("more");
        });
        //设置刷新加载时禁止所有列表操作
        binding.refreshLayout.setDisableContentWhenRefresh(true);
        binding.refreshLayout.setDisableContentWhenLoading(true);
        binding.refreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
        //
    }


    @SingleClick
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ssBtn_latest) {
            //binding.ssBtnLatest.setTextAppearance(R.style.SuperButton_Select);
           /* binding.ssBtnLatest.setTextColor(getResources().getColor(R.color.colorPrimary));
            binding.ssBtnRecommend.setTextColor(getResources().getColor(R.color.black_light_T9));
            binding.ssBtnNearby.setTextColor(getResources().getColor(R.color.black_light_T9));

            binding.ssBtnLatest.setBackgroundColor(getResources().getColor(R.color.select_btn_color_normal));
            binding.ssBtnRecommend.setBackgroundColor(getResources().getColor(R.color.xui_transparent));
            binding.ssBtnNearby.setBackgroundColor(getResources().getColor(R.color.xui_transparent));

            binding.ssBtnLatest.setShapeCornersRadius(12f);*/


        } else if (id == R.id.lt_search_box) {
            //点击搜索框
            openNewPage(JobListFragment.class);
        } else if (id == R.id.ssBtn_job) {
            //点击我要招工
            RxBusUtils.get().postRxEvent(EventKey.EVENT_BUTTON_RECRUIT_CLICK);
        } else if (id == R.id.ssBtn_recommend) {
           /* binding.ssBtnLatest.setTextColor(getResources().getColor(R.color.black_light_T9));
            binding.ssBtnRecommend.setTextColor(getResources().getColor(R.color.colorPrimary));
            binding.ssBtnNearby.setTextColor(getResources().getColor(R.color.black_light_T9));


            binding.ssBtnLatest.setBackgroundColor(getResources().getColor(R.color.xui_transparent));
            binding.ssBtnRecommend.setBackgroundColor(getResources().getColor(R.color.select_btn_color_normal));
            binding.ssBtnNearby.setBackgroundColor(getResources().getColor(R.color.xui_transparent));

            binding.ssBtnRecommend.setShapeCornersRadius(Float.intBitsToFloat(30));*/
        } else if (id == R.id.ssBtn_nearby) {
          /*  binding.ssBtnLatest.setTextColor(getResources().getColor(R.color.black_light_T9));
            binding.ssBtnRecommend.setTextColor(getResources().getColor(R.color.black_light_T9));
            binding.ssBtnNearby.setTextColor(getResources().getColor(R.color.colorPrimary));

            binding.ssBtnLatest.setBackgroundColor(getResources().getColor(R.color.xui_transparent));
            binding.ssBtnRecommend.setBackgroundColor(getResources().getColor(R.color.xui_transparent));
            binding.ssBtnNearby.setBackgroundColor(getResources().getColor(R.color.select_btn_color_normal));

            binding.ssBtnNearby.setShapeCornersRadius(12f);
            binding.ssBtnNearby.setShapeGradientGradientRadius(15);*/
        } else if (id == R.id.ssBtn_region) {
            pickCity();
        }
    }

    private void pickCity() {
        LocationService.get().init(getContext());
        LocationService.start(new OnBDLocationListener());
        checkPermission(getContext().getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION);
        CityPicker.from(this).enableAnimation(mEnableAnimation).setAnimationStyle(mAnim).setLocatedCity(null).setHotCities(mHotCities).setOnPickListener(new OnPickListener() {

            OnBDLocationListener mListener = new OnBDLocationListener();

            @SuppressLint("SuspiciousIndentation")
            @Override
            public void onPick(int position, City data) {
                //tvCurrent.setText(String.format("当前城市：%s，%s", data.getName(), data.getCode()));
                if (!data.getCode().equals("0")) {
                    binding.ssBtnRegion.setText(data.getName());
                    ssBtnRegionAddress.setText(data.getName());
                    jobInfoSearchRequest.setJobProvince(data.getProvince());
                    jobInfoSearchRequest.setJobCityName(data.getName());
                    getJobInfoList("fresh");
                }

                //XToastUtils.toast(String.format("点击的数据：%s，%s", data.getName(), data.getCode()));
                LocationService.stop(mListener);
            }

            @Override
            public void onCancel() {
                //XToastUtils.toast("取消选择");
                LocationService.stop(mListener);
            }

            @Override
            public void onLocate(final OnLocationListener locationListener) {
                //开始定位
                mListener.setOnLocationListener(locationListener);
                LocationService.start(mListener);
                               /*new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        //模拟定位成功
                                        locationListener.onLocationChanged(new LocatedCity("深圳", "广东", "101280601"), LocateState.SUCCESS);
                                    }
                                }, 5000);*/
            }

        }).show();
    }


    public static int checkPermission(Context context, String permission) {

        boolean allowedByPermission = true;
        try {
            int result = context.checkPermission(permission, android.os.Process.myPid(), android.os.Process.myUid());
            allowedByPermission = (result == PackageManager.PERMISSION_GRANTED);
        } catch (Exception e) {
            allowedByPermission = true;
        }
        if (!allowedByPermission) {
            return 0;
        } else {
            return 1;
        }
    }


    /**
     * 百度定位
     */
    public class OnBDLocationListener extends BDAbstractLocationListener {

        private OnLocationListener mOnLocationListener;

        public OnBDLocationListener setOnLocationListener(OnLocationListener onLocationListener) {
            mOnLocationListener = onLocationListener;
            return this;
        }

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (mOnLocationListener != null) {
                mOnLocationListener.onLocationChanged(LocationService.onReceiveLocation(bdLocation), LocateState.SUCCESS);
                LocationService.get().unregisterListener(this);
                //XToastUtils.toast(bdLocation.getCity());
            }
        }
    }

    /**
     * 需要在fragment每次切换都需要执行的方法，其他地方的方法因为viewpage框架缓存的原因只会执行一次。
     */
    @Override
    protected void startLazyData() {
        super.startLazyData();
        this.initTitle();
    }

    /**
     * 查询招聘信息列表数据
     *
     * @return
     */
    @SuppressLint("CheckResult")
    private void getJobInfoList(String type) {
        //binding.llStateful.showLoading();
        /*if(type.equals("fresh")){
            binding.refreshLayout.autoRefresh();
        }
        binding.llStateful.showContent();*/
        jobInfoSearchRequest.setLimit(pageSize);
        jobInfoSearchRequest.setStatus(Integer.valueOf(Constants.JOB_STATUS_RUNNING));
        XHttpProxy.proxy(TestApi.IJobService.class).jobInfList(jobInfoSearchRequest).subscribeWith(new NoTipRequestSubscriber<JobInfoPage>() {
            @Override
            protected void onSuccess(JobInfoPage commonPageApiResult) {
                Log.i(TAG, "-------------招工信息列表------------------");
                Log.i(TAG, GsonUtils.toJson(commonPageApiResult));
                if (type.equals("fresh")) {
                    mJobsAdapter.refresh(commonPageApiResult.getList());
                    binding.refreshLayout.finishRefresh();
                } else if (type.equals("more")) {
                    if (commonPageApiResult.getList().isEmpty()) {
                        binding.refreshLayout.finishLoadMoreWithNoMoreData();
                        ToastUtils.toast("已更新到最新数据");
                    } else {
                        mJobsAdapter.loadMore(commonPageApiResult.getList());
                        binding.refreshLayout.finishLoadMore();
                    }

                }
                binding.llStateful.showContent();

                //ToastUtils.toast("已更新最新数据");
                Log.i(TAG, "-------------招工信息列表------------------");
            }

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                binding.refreshLayout.finishRefresh();
                ToastUtils.toast(e.getDisplayMessage());
                binding.llStateful.showError("加载数据失败", "重试", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        getJobInfoList("fresh");
                    }
                });
                Log.i(TAG, "-------------招工信息列表-返回错误------------------");
                Log.e(TAG, e.getMessage());
            }

        });

    }

    @SuppressLint("CheckResult")
    private void getKingMenuList(Integer type, Integer target) {
        XHttpProxy.proxy(TestApi.IConfigService.class).getList(type, target).subscribeWith(new NoTipRequestSubscriber<List<CategoryMenuVo>>() {
            @Override
            protected void onSuccess(List<CategoryMenuVo> categoryMenuVoList) {
                Log.i(TAG, "-------------菜单信息列表------------------");
                Log.i(TAG, GsonUtils.toJson(categoryMenuVoList));

                if (!categoryMenuVoList.isEmpty()) {
                    container.removeAllViews();
                    bindKingMenu(null);//添加全部分类菜单
                    for (CategoryMenuVo menuVo : categoryMenuVoList) {
                        bindKingMenu(menuVo);
                    }
                }
                //ToastUtils.toast("已更新最新数据");
                Log.i(TAG, "-------------菜单信息列表------------------");
            }

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                binding.refreshLayout.finishRefresh();
                ToastUtils.toast(e.getDisplayMessage());
                Log.i(TAG, "-------------菜单信息列表-返回错误------------------");
                Log.e(TAG, e.getMessage());
            }
        });

    }

    public int Dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public int Px2Dp(Context context, float px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    @Override
    public void onDestroyView() {
        mJobsAdapter.recycle();
        super.onDestroyView();
    }

    //------//
    private void checkLocationPermission(){
        //检查是否获取了定位权限
        if(XXPermissions.isGranted(getContext(),Permission.ACCESS_FINE_LOCATION)) {
            //已获取定位权限
        }else {
            CustomDialog.show(new OnBindView<CustomDialog>(R.layout.layout_custom_location_dialog) {
                @Override
                public void onBind(final CustomDialog dialog, View v) {
                    Button btnOk;
                    btnOk = v.findViewById(R.id.btn_ok);
                    TextView textClose = v.findViewById(R.id.btn_close);
                    textClose.setOnClickListener(view -> dialog.dismiss());
                    btnOk.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                           //申请权限
                            applyLocationPermission();
                            dialog.dismiss();
                        }
                    });
                }
            }).setMaskColor(getResources().getColor(R.color.translucent_background));
        }
    }

    private void applyLocationPermission(){
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            toast("获取部分权限成功，但部分权限未正常授予");
                            return;
                        }
                        Toaster.show("已获取位置权限");
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            toast("被永久拒绝授权，请手动位置权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getContext(), permissions);
                        } else {
                            toast("获取位置权限失败");
                        }
                    }
                });
    }

}